package cn.com.zcode.core.cxf;

import java.io.File;
import java.util.jar.JarEntry;

import org.apache.log4j.Logger;

import cn.com.zcode.core.scan.ScanFilter;

/**
 * @author zeng.jinqing
 * @date Apr 19, 2013
 */
public class DefaultPublishClassFilter implements ScanFilter<Class<?>> {
	private Logger logger = Logger.getLogger(DefaultPublishClassFilter.class);
	private ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

	@Override
	public Class<?> pass(File file, String packageName) {
		String fileName = file.getName();
		if (fileName.endsWith(".class")) {
			String className = packageName + fileName.substring(0, fileName.length() - 6);
			Class<?> zclass = this.loadClass(className);
			if (!zclass.isInterface() && zclass.getAnnotation(AutoPublish.class) != null) {
				return zclass;
			}

		}
		return null;
	}

	@Override
	public Class<?> pass(JarEntry entry, String packageName) {
		String fileName = entry.getName();
		if (fileName.endsWith(".class")) {
			String className = fileName.replace('/', '.');
			if (className.startsWith(packageName)) {
				className = className.substring(0, fileName.length() - 6);
				Class<?> zclass = this.loadClass(className);
				return zclass;
			}
		}
		return null;
	}

	private Class<?> loadClass(String className) {
		try {
			Class<?> zclass = Class.forName(className, false, classLoader);
			return zclass;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
}
